import React, {
    Component,
    useState, 
    useRef 
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;

let navigation


export default class SignatoryPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            contractTitle:'',//合同名称
            templateId:'',//合同模板id
            templateName:'',//合同模板名称
            templateList:[],//需要填写或者展示的签署方信息
            // submitTemplateInfos:{},
            currentChooseItem:[],//当前选中的
            textInputs:[],
            customComponents:[],
            chooseType:''
        }
    }

    componentWillUnmount() {
        if (this.commonEventLinster) {
            this.commonEventLinster.remove()
        }
     
        
    }

    componentDidMount() {
        let id = this.props.route.params.templateId
        let choose = this.props.route.params.chooseType ? this.props.route.params.chooseType:''
        this.setState({
            templateId:id,
            chooseType:choose
        }, function () {
            this.getTemplateInfo()
        })
        this.commonEventLinster = DeviceEventEmitter.addListener('commonEvent', e => {
          
         //选择了客户的回调
         if(e.eventName && e.eventName == 'chooseCustomer'){
            if(e.mobile){
                this.onChangeTemplateInfo(this.state.currentChooseItem,'','mobile',e.mobile)
                this.onChangeTemplateInfo(this.state.currentChooseItem,'','name',e.name)
       
               const updatedTemplateList = this.state.templateList.map(model => {
                   // 检查 participantId 是否匹配
                   if (model.participantId === this.state.currentChooseItem.participantId) {
                       // 返回一个新的对象，更新 psnParticipant
                       return {
                           ...model, // 保留其他属性
                           psnParticipant: {
                               psnAccount: e.mobile,
                               psnName: e.name,
                           },
                       };
                   }
                   return model; // 返回未更改的对象
               });
       
               // 使用 setState 更新状态
               this.setState({
                   templateList: updatedTemplateList
               }, function () {
                 
               })
            }
     
         }else if(e.type &&  e.type == 'selectCompanyResult'){

            //选择了商家的回调
            if(e.phone ){
                this.onChangeTemplateInfo(this.state.currentChooseItem,'','mobile',e.phone)
                this.onChangeTemplateInfo(this.state.currentChooseItem,'','name',e.owner)
                this.onChangeTemplateInfo(this.state.currentChooseItem,'','orgName',e.merchantName)
    
            const updatedTemplateList = this.state.templateList.map(model => {
                // 检查 participantId 是否匹配
                if (model.participantId === this.state.currentChooseItem.participantId) {
                    // 返回一个新的对象，更新 psnParticipant
                    return {
                        ...model, // 保留其他属性
                        orgParticipant: {
                            orgName:e.merchantName,
                            transactor:{
                                transactorPsnAccount:e.phone,
                                transactorName:e.owner
                                        }
                                    },
                                };
                            }
                            return model; // 返回未更改的对象
                        });
    
                        // 使用 setState 更新状态
                        this.setState({
                            templateList: updatedTemplateList
                        }, function () {
                            
                        })
            }
           
                }

        });

  


        
    }



    getTemplateInfo(){
        
        let param = {
            merchantId: Constant.userInfo.merchantId,
            templateId:this.state.templateId
        }
        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.templateInfo, param)
        .then((result) => {
            if (this.Loading) {
                this.Loading.hide();
            }
            // console.log('====>>>>>>>>>>>>>>>>>2222')
            // console.log(result.data.templateInfo)
            // console.log('====>>>>>>>>>>>>>>>>>1111')
            let code = result.code
            if (code == 0) {

                const initialState = result.data.templateInfo.participants.reduce((acc, item) => {
           
                    // if(item.participantType == 2){
                    //     if(item.psnParticipant && item.psnParticipant.psnName){
                    //         acc[item.participantId]['name'] = item.psnParticipant.psnName;
                    //     }
                    //     if(item.psnParticipant && item.psnParticipant.psnAccount){
                    //         acc[item.participantId]['mobile'] = item.psnParticipant.psnAccount;
                    //     }
                    // }else {
                    //     if(item.orgParticipant && item.orgParticipant.orgName){
                    //         acc[item.participantId]['orgName'] = item.orgParticipant.orgName;
                    //     }
                        
                    //     if(item.orgParticipant && item.orgParticipant.transactor && item.orgParticipant.transactor.transactorName){
                    //         acc[item.participantId]['name'] = item.orgParticipant.transactor.transactorName;
                    //     }
                    //     if(item.orgParticipant && item.orgParticipant.transactor && item.orgParticipant.transactor.transactorPsnAccount){
                    //         acc[item.participantId]['mobile'] = item.orgParticipant.transactor.transactorPsnAccount;
                    //     }
                    // }
                

                    return acc;
                  }, {});
           
                this.setState({
                    templateName:result.data.templateName,
                    templateList:result.data.templateInfo.participants,
                    textInputs: initialState,
                    contractTitle:result.data.templateName,
                    customComponents:result.data.customComponents
                })

            }else {
                ToastToUser(result.msg)
            }
        })
        .catch((error) => {

        });
    }

    render() {
        navigation = this.props.navigation
        const textColor = this.state.templateName ? '#333333' : '#999999';
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'填写签署方'} />
                <ScrollView
                    keyboardShouldPersistTaps="handled"
                >
                {/* 合同模板 */}
                <TouchableOpacity 
                    activeOpacity={0.8}
                    onPress={this.chooseTemplate.bind(this)}
                >
                    <View style={styles.commonConainer}>
                        <Text style={[styles.commonTitle,{marginLeft:15}]}>合同模版</Text>
                        <Text style={[styles.commonValue,{color: textColor}]}>{this.state.templateName?this.state.templateName:'请先选择合同模板'}</Text>
                        <Image source={require('source/image/electron/selectarrow.png')} style={styles.selectarrow} />
                        <View style={styles.borderBottom} >
                        </View>
                    </View>
                </TouchableOpacity>
                {/* 合同名称 */}
                <View style={[styles.commonConainer,{marginTop:0}]}>
                    <Text style={[styles.commonTitle,{marginLeft:15}]}>合同名称</Text>
                    <TextInput
                        editable={true}
                        style={styles.inputbox}
                        placeholder='请输入合同名称'
                        placeholderTextColor={'#999999'}
                        value={this.state.contractTitle}
                        onChangeText={this.onChangeTextHandle.bind(this)}
                    ></TextInput>
                </View>

                {/* 需填写信息提示 */}
                {
                    this.state.templateList.length>0
                    ?
                    <View style={styles.tips}>
                        <Text style={styles.signInfo}>签署方信息</Text>
                        <View style={styles.signContainer}>
                            <Text style={styles.signTopInfo}>个人签署方：须确保填写的手机号注册的姓名与合同中签署方姓名完全一致</Text>
                            <Text style={styles.signTopInfo}>企业签署方：须填写营业执照上的企业名称</Text>
                        </View>
                    </View>
                    :
                    null
                
                }
{/* 
                <FlatList
                    data={this.state.templateList}
                    renderItem={this.renderItemView.bind(this)}
                    keyExtractor={item => item.participantId}
                /> */}


                {/* 签署方信息提示 */}
                {
                    this.state.templateList
                    ?
                        <View>
                          {this.state.templateList.map((item,index) => (
                            <View key={index}>
                                {/* 需要输入的信息 */}
                                <View style={styles.commonSignContainer} >
                                    {/* 头部的选择商家还是客户 */}
                                    <View style={styles.signItemContainer}>
                                        <Text style={styles.siginItemType}>{item.participantFlag}</Text>
                                        <View style={styles.signTypeContainer}>
                                            <Text style={styles.signTypeTitle}>{item.participantType == 2 ? '个人':'企业'}</Text>
                                        </View>

                                        <TouchableOpacity style={styles.signItemChoose}
                                          onPress={this.chooseSignItem.bind(this,item,index)}
                                        >
                                            {
                                                // 这两个状态表示要回显
                                                (item.participantSetMode == 2 || item.participantSetMode == 4)
                                                ?
                                                null
                                                :
                                                <Text style={styles.signItemChooseTitle}>{item.participantType == 2 ? '请选择客户':'请选择商家'}</Text>
                                            }
                                        </TouchableOpacity>
                                        <View style={styles.borderBottom} >
                                        </View>
                                    </View>
                                    {/* 输入的企业名称 */}
                                    {
                                        item.participantType == 2
                                        ?
                                        null
                                        :
                                        <View style={styles.signItemContainer}>
                                        <Text style={styles.signItemCompanyTitle}>企业名称</Text>
                                        {
                                            (item.participantSetMode == 2 || item.participantSetMode == 4)
                                            ?
                                            <Text
                                            style={styles.inputSignCompanyMoren}
                                            >{item.orgParticipant.orgName}</Text>
                                            :
                                            <TextInput
                                            editable={true}
                                            style={styles.inputSignCompany}
                                            placeholder='请输入企业名称'
                                            placeholderTextColor={'#999999'}
                                            value={this.getRealCompany(item)}
                                            onChangeText={this.onChangeTemplateInfo.bind(this,item,index,'orgName')}
                                            ></TextInput>
                                        }
                                        <View style={styles.borderBottom} >
                                        </View>
                                    </View>
                                        
                                    }
                               
                                    {/* 输入的姓名 */}
                                    <View style={styles.signItemContainer}>
                                        <Text style={styles.signItemCompanyTitle}>姓名</Text>
                                        {
                                        (item.participantSetMode == 2 || item.participantSetMode == 4)
                                            ?
                                            <Text
                                            style={styles.inputSignCompanyMoren}
                                            >
                                            {item.participantType == 2 ?item.psnParticipant.psnName: item.orgParticipant.transactor.transactorName}
                                            </Text>
                                            :
                                        <TextInput
                                            editable={true}
                                            style={styles.inputSignCompany}
                                            placeholder='请输入真实姓名'
                                            value={this.getRealName(item)}
                                            placeholderTextColor={'#999999'}
                                            onChangeText={this.onChangeTemplateInfo.bind(this,item,index,'name')}
                                            // onChangeText={(text) => this.onChangeTemplateInfo1(item, text)}

                                            ></TextInput>
                                        }
                                        <View style={styles.borderBottom} >
                                        </View>
                                    </View>
        
                                    {/* 输入的手机号 */}
                                    <View style={styles.signItemContainer}>
                                            <Text style={styles.signItemCompanyTitle}>手机号</Text>
                                            {
                                        (item.participantSetMode == 2 || item.participantSetMode == 4)
                                            ?
                                            <Text
                                            style={styles.inputSignCompanyMoren}
                                            >
                                                {item.participantType == 2 ?item.psnParticipant.psnAccount: item.orgParticipant.transactor.transactorPsnAccount}
                                            </Text>
                                            :
                                            <TextInput
                                                editable={true}
                                                style={styles.inputSignCompany}
                                                placeholder='请输入手机号'
                                                maxLength={11}
                                                value={this.getRealMobile(item)}
                                                keyboardType="numeric"
                                                placeholderTextColor={'#999999'}
                                                onChangeText={this.onChangeTemplateInfo.bind(this,item,index,'mobile')}
                                                ></TextInput>
                                            }
                                    </View>
                                </View>
                           </View>
                          ))}
                        </View>
                    :
                    null
                }

                {/* 下一步 */}
                {
                    this.state.templateList.length>0
                    ?
                    <TouchableOpacity
                    onPress={this.submit.bind(this)}
                    >
                        <View 
                             style={styles.nextContaner}
                        >
                            <Text style={styles.nextTitle}>下一步</Text>
                        </View>
                    </TouchableOpacity>
                    :
                    null
                }
                
                </ScrollView>

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    getRealName(item){
     
        return this.state.textInputs[item.participantId+'name'];

    }

    getRealMobile(item){
        return this.state.textInputs[item.participantId+'mobile'];

    }

    getRealCompany(item){
        return this.state.textInputs[item.participantId+'orgName'];
    }

     // 输入的合同名称
    onChangeTextHandle = (value) => {
        this.setState({ contractTitle: value });
    }

    // 选择模板
    chooseTemplate(){
        navigation.goBack()
    }

    //选择商家或者客户
    chooseSignItem(item,index){
     
        this.setState({
            currentChooseItem:item
        }, function () {
            if(item.participantType == 1){
                //选择商家
                this.chooseCompany()
            }else{
                //选择客户
                navigation.navigate('ChooseCustomersPage')
            }
        })


    
    }

    chooseCompany(){

        try {
            AndroidModule.selectCompany({})
        } catch (error) {
            
        }
        
    }

        // onChangeTemplateInfo1 = (item, text) => {
        //     this.setState((prevState) => ({
        //         textInputs: {
        //           ...prevState.textInputs,
        //           [item.participantId]: text,
        //         },
        //       }));
        // }

    //输入的企业名称，姓名或者手机号
    onChangeTemplateInfo= (item,index,field,value) => {
      

        this.setState((prevState) => ({
            textInputs: {
              ...prevState.textInputs,
              [item.participantId+field]: value,
            },
          }));


        for(let i = 0;i < this.state.templateList.length;i++){
            let model = this.state.templateList[i]
            if(model.participantId	== item.participantId){
                if(item.participantType == 2){
                    //个人
                    //手机号
                    if(field == 'mobile'){
                        if(!model['psnParticipant']){
                            model['psnParticipant'] ={}
                            item['psnParticipant']={}
                        }
                        model['psnParticipant']['psnAccount']=value
                        item['psnParticipant']['psnAccount']=value
                    }
                    //姓名
                    if(field == 'name'){
                        if(!model['psnParticipant']){
                            model['psnParticipant'] ={}
                            item['psnParticipant'] ={}
                        }
                        model['psnParticipant']['psnName']=value
                        item['psnParticipant']['psnName']=value
                    }
                }else{
                    //企业
                        //企业名称
                        if(field == 'orgName'){
                            if(!model['orgParticipant']){
                                model['orgParticipant'] ={}
                                item['orgParticipant'] ={}
                            }
                            model['orgParticipant']['orgName']=value
                            item['orgParticipant']['orgName']=value
                        }
                        //姓名
                        if(field == 'name'){
                            if(!model['orgParticipant']){
                                model['orgParticipant'] ={}
                                item['orgParticipant'] ={}
                            }
                            if(!model['orgParticipant']['transactor']){
                                model['orgParticipant']['transactor'] ={}
                                item['orgParticipant']['transactor'] ={}
                            }
                            model['orgParticipant']['transactor']['transactorName']=value
                            item['orgParticipant']['transactor']['transactorName']=value
                        }
                        //手机号
                        if(field == 'mobile'){
                        if(!model['orgParticipant']){
                            model['orgParticipant'] ={}
                            item['orgParticipant'] ={}
                        }
                        if(!model['orgParticipant']['transactor']){
                            model['orgParticipant']['transactor'] ={}
                            item['orgParticipant']['transactor'] ={}
                        }
                        model['orgParticipant']['transactor']['transactorPsnAccount']=value
                        item['orgParticipant']['transactor']['transactorPsnAccount']=value
                    }

                }
                break
            }
     }

   
    }

    submit(){
        if (!this.state.contractTitle) {
            ToastToUser('请先输入合同名称')
            return;
        }

        if (!this.state.templateName) {
            ToastToUser('请先选择合同模板')
            return;
        }


        for(let i = 0;i < this.state.templateList.length;i++){
            let item=this.state.templateList[i]

            if(item.participantSetMode == 2 || item.participantSetMode == 4){
                continue
            }
            if(item.participantType == 1 ){
                if(!item.orgParticipant || !item.orgParticipant.transactor){
                    ToastToUser('请先填写'+item.participantFlag+'的相关信息')
                    return;
                }else if(!item.orgParticipant.orgName){
                    ToastToUser('请先输入'+item.participantFlag+'的企业名称')
                    return;
                }else if(!item.orgParticipant.transactor.transactorPsnAccount){
                    ToastToUser('请先输入'+item.participantFlag+'的手机号')
                    return;
                }else if(item.orgParticipant.transactor.transactorPsnAccount.length !=11){
                    ToastToUser(item.participantFlag+'的手机号必须为11位')
                    return;
                }else if(!item.orgParticipant.transactor.transactorName){
                    ToastToUser('请先输入'+item.participantFlag+'的真实姓名')
                    return;
                }
            }else{
                if(!item.psnParticipant){
                    ToastToUser('请先填写'+item.participantFlag+'的相关信息')
                    return;
                }else if(!item.psnParticipant.psnAccount){
                    ToastToUser('请先输入'+item.participantFlag+'的手机号')
                    return;
                }else if(item.psnParticipant.psnAccount.length !=11){
                    ToastToUser(item.participantFlag+'的手机号必须为11位')
                    return;
                }else if(!item.psnParticipant.psnName){
                    ToastToUser('请先输入'+item.participantFlag+'的真实姓名')
                    return;
                }
            }
   
        }


        // let tempArr=[]
        // for(let i = 0;i < this.state.templateList.length;i++){
        //     let model=this.state.templateList[i]
        //     let item={}

        //     item.participantId=model.participantId
        //     if(model.participantType == 1){
        //         item.orgName=model.orgParticipant.orgName
        //         item.transactorPsnAccount=model.orgParticipant.transactor.transactorPsnAccount
        //         item.transactorName=model.orgParticipant.transactor.transactorName
        //     }else{
        //         item.psnAccount=model.psnParticipant.psnAccount
        //         item.psnName=model.psnParticipant.psnName
        //     }
        //     tempArr.push(item)
        // }
        // console.log(tempArr)

        let params = {
            templateList: JSON.stringify(this.state.templateList),
            templateId: this.state.templateId+'',
            templateName:this.state.templateName,
            contractName:this.state.contractTitle,
            customComponents:JSON.stringify(this.state.customComponents),
            chooseType:this.state.chooseType
        }
        navigation.navigate('FillContractPage', params)
    }


}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6'
    },

    commonConainer:{
        height:46,
        backgroundColor:'#ffffff',
        marginTop:10,
        alignItems:'center',
        flexDirection:'row',
   
    },

    commonTitle:{
        fontWeight: '400',
        fontSize: 14,
        color: '#333333'
    },

    commonValue:{
        position:'absolute',
        marginLeft:110,
        fontWeight: '400',
        fontSize: 14,
        color: '#999999'
    },

    selectarrow:{
        width:17,
        height:17,
        position:'absolute',
        right:15
    },

    borderBottom:{
        borderBottomColor:'#E4E4E4',
        borderBottomWidth:1,
        marginLeft:15,
        width:'100%',
        position:'absolute',
        bottom:0
    },

    inputbox:{
        width:'100%',
        height:'100%',
        left:110,
        position:'absolute',
        fontSize: 14,
        padding: 0, 
        margin:0,
    },

    tips:{
        backgroundColor:'#ffffff',
        width:'100%',
        marginTop:10,
    },

    signInfo:{
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
        marginLeft:16,
        marginTop:12
    },

    signContainer:{
        marginLeft:16,
        marginRight:16,
        marginTop:12,
        marginBottom:12,
        backgroundColor:'#F4F4F4',
        height:102,
        width: screenW-32,
    },

    signTopInfo:{
        marginLeft:12,
        marginTop:12,
        marginRight:12,
        fontSize: 14,
        color: '#333333',
        fontWeight: '400',
        lineHeight: 22,
    },

    commonSignContainer:{
        marginTop:10,
        backgroundColor:'#ffffff'
    },

    signItemContainer:{
        flexDirection:'row',
        height:46,
        alignItems:'center'
    },

    siginItemType:{
        marginLeft:16,
        fontSize: 14,
        color: '#333333',
        fontWeight: '500',
    },

    signTypeContainer:{
        marginLeft:6,
        width:36,
        height:16,
        borderRadius:1,
        borderColor:'#E5E5E5',
        alignItems:'center',
        justifyContent:'center',
        borderWidth: 1,
    },

    signTypeTitle:{
        fontSize: 10,
        color: '#666666',
        fontWeight: '500',
    },

    signItemChoose:{
        position:'absolute',
        right:16
    },

    signItemChooseTitle:{
        fontSize: 14,
        color: '#F99802',
        fontWeight: '400', 
    },

    signItemCompanyTitle:{
        fontSize: 14,
        color: '#333333',
        fontWeight: '400', 
        marginLeft:16
    },

      inputSignCompanyMoren:{
        left:110,
        position:'absolute',
        fontSize: 14,
        color: '#333333',
        fontWeight: '400', 
    },

    inputSignCompany:{
        width:'100%',
        height:'100%',
        left:110,
        position:'absolute',
        fontSize: 14,
        padding: 0, 
        margin:0,
    },

    nextContaner:{
        marginLeft:16,
        marginRight:16,
        width: screenW-32,
        height:46,
        borderRadius: 4,
        backgroundColor:'#FFE000',
        alignItems:'center',
        justifyContent:'center',
        marginTop:30,
        marginBottom:30
    },

    nextTitle:{
        fontSize: 15,
        color: '#222222',
        fontWeight: '400', 

    }






})